package com.qing.config.security.service.impl;

import com.qing.config.security.mapper.UsersMapper;
import com.qing.config.security.pojo.JwtUser;
import com.qing.config.security.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 竹秋廿四
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Users user = usersMapper.login(username);

        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        List<GrantedAuthority> userRole = new ArrayList<>();
        if (user.getStatus() == 1) {
            userRole = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin");
        } else if (user.getStatus() == 2) {
            userRole = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_user");
        }

        return new JwtUser(user, userRole);

    }


}
